define(
   [
      'dojo/_base/declare',
      'dojo/_base/lang',
      'noBusinessBase/heartbeat/Connection'
   ],
   function(declare, lang, Connection)
   {
      return declare([Connection],
      {
         mLongPollId: null,
         mLongPollInterval: 2000,
         mLongPollPass: null,
         mLongPollTimerId: null,
         constructor:function(args)
         {
            dojo.safeMixin(this, args);
         },
         postscript: function(args)
         {
            this.inherited(arguments);
            var xhrArgs = 
            {
               url: '/long-poll/connect',
               handleAs:'json',
               load: lang.hitch(this, function(data)
               {
                  //Use the retData from the script.
                  this.mLongPollId = data.connectionId;
                  this.mLongPollPass = data.password;

                  //Create the long poll updater function.
                  var updateFunc = lang.hitch(this, function()
                  {
                     var xhrUpdateArgs = 
                     {
                        url: '/long-poll/updates/connectionId/' + this.mLongPollId + '/password/' + this.mLongPollPass,
                        handleAs:'json',
                        load: lang.hitch(this, function(data)
                        {
                           if(!data)
                           {
                              this.close();
                              return;
                           }

                           for(var i = 0; i < data.messages.length; ++i)
                              this.onMessage(data.messages[i]);
                        }),
                        error: lang.hitch(this, function(error)
                        {
                           this.close();
                        })
                     };
                     dojo.xhrGet(xhrUpdateArgs);
                  });

                  //Run the function once now to get an immediate update.
                  updateFunc();

                  //Schedule periodic updates.
                  this.mLongPollTimerId = setInterval(lang.hitch(this, updateFunc), this.mLongPollInterval);
               }),
               error: function(error)
               {
                  console.log(error);
               }
            };

            dojo.xhrGet(xhrArgs);
         },
         write: function(jsonStr)
         {
            var xhrArgs = 
            {
               url: '/long-poll/message/connectionId/' + this.mLongPollId + '/password/' + this.mLongPollPass,
               postData: jsonStr
            };

            dojo.xhrPost(xhrArgs);   

            this.inherited(arguments);
         },
         close: function()
         {
            if(!this.mLongPollTimerId)
               return;

            clearInterval(this.mLongPollTimerId);
            this.mLongPollTimerId = null;
            this.inherited(arguments);
            this.onClose();
         }
      });
   }
);
